package com.bifrost.admin.controller;

import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.annotation.CurrentStore;
import com.bifrost.constant.MerchantConfigurationType;
import com.bifrost.entity.*;
import com.bifrost.model.AreaModel;
import com.bifrost.model.ConfigurationModel;
import com.bifrost.model.ResultModel;
import com.bifrost.model.StoreModel;
import com.bifrost.model.ro.StoreRO;
import com.bifrost.model.vo.MerchantStoreVO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.repository.*;
import com.bifrost.service.AdminUserService;
import com.bifrost.service.JedisService;
import com.bifrost.service.MerchantConfigurationService;
import com.bifrost.service.StoreService;
import com.bifrost.util.TransformUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 *  @Author:Sophia
 *  @Date:2018/4/3
 *  
 */
@RestController
@Api("后台门店相关接口")
@RequestMapping("/admin/store")
public class MerchantController {

    @Autowired
    StoreService storeService;
    @Autowired
    CountryAreaRepository countryAreaRepository;
    @Autowired
    private JedisService jedisService;
    @Autowired
    MerchantStoreRepository merchantStoreRepository;
    @Autowired
    AdminUserRepository adminUserRepository;
    @Autowired
    private AdminUserService userService;
    @Autowired
    MerchantConfigurationService configurationService;
    @Autowired
    MerchantConfigurationRepository configurationRepository;
    @Autowired
    ConfigurationAliasRepository aliasRepository;

    @ApiOperation("获取门店信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "page", value = "当前页", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页数量", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "storeName",dataType = "String",value = "门店名称",required = false),
            @ApiImplicitParam(paramType = "query",name = "areaId",dataType = "String",value = "区域ID",required = false),
            @ApiImplicitParam(paramType="query",name = "storeCode",dataType = "String",value = "门店编码",required = false),
            @ApiImplicitParam(paramType="query",name = "externalIds",dataType = "String",value = "SAP编码",required = false)
    })
    @GetMapping("/all")
    public ResultModel getMerchantStoreInfo(@RequestParam(value = "page", defaultValue = "1") String page, @RequestParam(value = "pageSize", defaultValue = "10") String pageSize, String storeName, @RequestParam(value = "areaId", defaultValue = "0")  String areaId, String storeCode, String externalIds){
        Page<MerchantStore> data=storeService.getAdminMerchantStores(Integer.parseInt(page),Integer.parseInt(pageSize),storeName,Long.parseLong(areaId),storeCode,externalIds);
        if (data!=null&&data.hasContent()){
            List<MerchantStore> merchantStores=data.getContent();
            if (CollectionUtils.isEmpty(merchantStores)){
                ResultModel.error("未找到数据");
            }
            List<StoreModel> storeModels=new ArrayList<>(merchantStores.size());
            List<AreaModel> areaModels=new ArrayList<>(merchantStores.size());
            merchantStores.forEach(merchantStore->{
                storeModels.add(TransformUtils.transformToStoreModel(merchantStore));
                //获取区，好按照区域去选门店
                CountryArea countryArea=merchantStore.getStoreDistrict();
                AreaModel info=new AreaModel(countryArea.getId(),countryArea.getName());
                areaModels.add(info);
            });
            //去掉重复区域
            List<AreaModel> districtAreas=areaModels.stream().distinct().collect(Collectors.toList());
/*            //按照门店排序号排序
            List<StoreModel> sortedModel=storeModels.stream().sorted(Comparator.comparing(StoreModel::getSortOrder)).collect(Collectors.toList());*/

            PageVO vo=new PageVO(data.getNumber(),data.getSize(),(int)data.getTotalElements(),storeModels);
            return ResultModel.ok("成功")
                    .put("areaDistrict",districtAreas)
                    .put("data",vo);
        }
        return ResultModel.error("未找到数据");
    }


    @ApiOperation("获取经理关联门店信息")
    @GetMapping("/mangerStore")
    public ResultModel getStoreInfo(){
        List<MerchantStore> merchantStores=storeService.getAllMerchantStores();
            if (CollectionUtils.isEmpty(merchantStores)){
                ResultModel.error("未找到数据");
            }
            List<StoreModel> storeModels=new ArrayList<>(merchantStores.size());
            merchantStores.forEach(merchantStore->{
                storeModels.add(TransformUtils.transformToStoreModel(merchantStore));
            });
            //按照门店排序号排序
            List<StoreModel> sortedModel=storeModels.stream().sorted(Comparator.comparing(StoreModel::getSortOrder)).collect(Collectors.toList());
            return ResultModel.ok("成功").put("store",sortedModel);
    }


    @ApiOperation("获取门店详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "merchantId",dataType = "Long",value = "门店ID",required = true)
    })
    @GetMapping("/detail")
    public ResultModel getMerchantStore(@RequestParam Long merchantId){
        MerchantStore merchantStore=storeService.getMerchantStore(merchantId);
        if (merchantStore==null){
            return ResultModel.error("未找到数据");
        }
        StoreRO store=new StoreRO();
        BeanUtils.copyProperties(merchantStore,store);
        store.setStateId(merchantStore.getStoreState().getId());
        store.setDistrictId(merchantStore.getStoreDistrict().getId());
        store.setCityId(merchantStore.getStoreCity().getId());
        return ResultModel.ok("成功").put("store",store);
    }

    @ApiOperation("新增门店信息")
    @PostMapping("/add")
    public ResultModel addMerchantStore(@CurrentAdmin Long userId, @RequestBody StoreRO store){
        User user = userService.findById(userId);
        MerchantStore merchantStore=new MerchantStore();
        BeanUtils.copyProperties(store,merchantStore);
        //TODO 设置其余属性
        merchantStore.setStoreState(countryAreaRepository.findOne(store.getStateId()));
        merchantStore.setStoreCity(countryAreaRepository.findOne(store.getStateId()));
        merchantStore.setStoreDistrict(countryAreaRepository.findOne(store.getDistrictId()));
        merchantStore.setUpdatedBy(user.getAdminName());
        merchantStore.setUpdatedTimestamp(new Date());
        if (StringUtils.isBlank(store.getStoreStreet())){
            merchantStore.setStoreAddress((countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getDistrictId()).getName()).trim());
        }else{
            merchantStore.setStoreAddress((countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getDistrictId()).getName()+store.getStoreStreet()).trim());
        }
        merchantStore=storeService.save(merchantStore);
        return ResultModel.ok("成功");
    }

    @ApiOperation("更新门店信息")
    @PostMapping("/update")
    public ResultModel updateMerchantStore(@CurrentAdmin Long userId, @RequestBody StoreRO store){
        if (store.getMerchantId()==null){
            return ResultModel.error("该门店不存在");
        }
        User user = userService.findById(userId);
        MerchantStore merchantStore=new MerchantStore();
        BeanUtils.copyProperties(store,merchantStore);
        //TODO 设置其余属性
        merchantStore.setStoreState(countryAreaRepository.findOne(store.getStateId()));
        merchantStore.setStoreCity(countryAreaRepository.findOne(store.getCityId()));
        merchantStore.setStoreDistrict(countryAreaRepository.findOne(store.getDistrictId()));
        MerchantStore checkStore=storeService.getMerchantStore(merchantStore.getMerchantId());
        merchantStore.setUpdatedBy(user.getAdminName());
        merchantStore.setUpdatedTimestamp(new Date());
        if (StringUtils.isBlank(store.getStoreStreet())){
            merchantStore.setStoreAddress((countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getDistrictId()).getName()).trim());
        }else{
            merchantStore.setStoreAddress((countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getStateId()).getName()+countryAreaRepository.findOne(store.getDistrictId()).getName()+store.getStoreStreet()).trim());
        }
        if (checkStore==null){
            return ResultModel.error("该门店不存在");
        }
        merchantStore=storeService.save(merchantStore);
        if (merchantStore==null){
            return ResultModel.error("更新数据失败");
        }
        return ResultModel.ok("成功");
    }

    @ApiOperation("删除门店")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "merchantIds",dataType = "String",required = true)
    })
    @PostMapping("/delete")
    public ResultModel deleteMerchantStore(@RequestParam String merchantIds){
        if(StringUtils.isEmpty(merchantIds)){
            return ResultModel.error("门店不存在");
        }
        storeService.deleteByMerchantId(merchantIds);
        return ResultModel.ok("成功");
    }

    @ApiOperation("根据id获取门店信息")
    @GetMapping("/merchants")
    public ResultModel selectStoreWithIds(@CurrentAdmin Long currentUser, Long merchantId, String merchantName, String merchantCode, @RequestParam(defaultValue = "1") Integer pageCode, @RequestParam(defaultValue = "10") Integer pageSize){
        try{
            boolean isshow;
            //获取当前登录用户的门店权限
            PageVO pageVO = storeService.havePermission(userService.findById(currentUser) ,merchantId,merchantName,merchantCode,pageCode,pageSize);
            List recordList = pageVO.getRecordList();
            if(CollectionUtils.isEmpty(recordList)){
                return ResultModel.error("门店信息查询失败");
            }else if(recordList.size() == 1){
                isshow = false;
            }else {
                isshow = true;
            }
            return ResultModel.ok("成功").put("pageVO",pageVO).put("isShow",isshow);
        }catch (Exception e){
            e.printStackTrace();
            return ResultModel.error("出现一些未知错误");
        }
    }
    @ApiOperation("获取登录人员所有门店")
    @GetMapping("/merchantsAll")
    public  ResultModel selectStoreWithAll(@CurrentAdmin Long currentUser, Long merchantId, String merchantName, String merchantCode){
        try {
           List<MerchantStoreVO> merchantStoreVOList = storeService.havaPermissionWithUser(userService.findById(currentUser) ,merchantId,merchantName,merchantCode);
            if (CollectionUtils.isEmpty(merchantStoreVOList)){
                return ResultModel.error("门店信息查询失败");
            }
            return ResultModel.ok("成功").put("list",merchantStoreVOList);
        }catch (Exception e){
            e.printStackTrace();
            return ResultModel.error("出现一些未知错误");
        }
    }

    @ApiOperation("获取登录人员门店")
    @GetMapping("/user_merchants")
    public  ResultModel selectStoreWithAll(@CurrentAdmin Long currentUser){
        List<MerchantStoreVO> merchantStoreVOList = new ArrayList<>();
            userService.findById(currentUser).getMerchantStores().forEach(merchantStore -> {
                MerchantStoreVO merchantStoreVO=  new MerchantStoreVO();
                BeanUtils.copyProperties(merchantStore, merchantStoreVO);
                merchantStoreVO.setStoreCode(merchantStore.getExternalId());
                merchantStoreVOList.add(merchantStoreVO);
        });
        if (CollectionUtils.isEmpty(merchantStoreVOList)){
            return ResultModel.error("请先配置门店信息");
        }
        return ResultModel.ok("成功").put("result",merchantStoreVOList);
    }

    @ApiOperation("门店配置添加")
    @PostMapping("/config/add")
    public  ResultModel configurationAdd(@RequestBody List<ConfigurationModel> configurationModels ,  @CurrentAdmin Long currentUser , @CurrentStore Long storeId ){
        configurationService.save(configurationModels,storeService.getMerchantStore(storeId),userService.findById(currentUser));
        return ResultModel.ok("保存成功");
    }


    @ApiOperation("门店配置修改")
    @PostMapping("/config/update")
    public  ResultModel configurationUpdate(@RequestBody List<ConfigurationModel> configurationModels ,  @CurrentAdmin Long currentUser , @RequestParam("storeId") Long storeId ){
        configurationService.update(configurationModels,storeService.getMerchantStore(storeId),userService.findById(currentUser));
        return ResultModel.ok("保存成功");
    }

    @ApiOperation("门店配置列表")
    @GetMapping("/config/list")
    public  ResultModel configurationList(@RequestParam("type") String type , @RequestParam("storeId")  Long storeId ){

        MerchantConfigurationAlias alias = aliasRepository.findFirstByMerchantConfigurationType(configurationService.getType(type));
        Assert.notNull(alias,"配置信息不存在");
        List<MerchantConfiguration> content = configurationRepository.findByMerchantStoreAndConfigurationAlias(storeService.getMerchantStore(storeId), alias);
        HashMap<Object, Object> aliasMap = Maps.newHashMap();
        ArrayList<ConfigurationModel> list = Lists.newArrayList();
        for (int i = 0; i < content.size(); i++) {
            MerchantConfiguration configuration = content.get(i);
            ConfigurationModel model = new ConfigurationModel();
            BeanUtils.copyProperties(configuration,model);
            model.setType(configuration.getMerchantConfigurationType().name());
            list.add(model);
        }
            // 配置参数别名展示key
            aliasMap.put("typeAlias",alias.getTypeAlias());
            aliasMap.put("keyAlias",alias.getKeyAlias());
            aliasMap.put("valueAlias",alias.getValueAlias());
        return ResultModel.ok().put("data",list).put("alias",aliasMap);
    }

    @ApiOperation("门店配置类型列表")
    @GetMapping("/config/type")
    public  ResultModel configurationTypes( @RequestParam("storeId") Long storeId ){
        List<Map> list = configurationService.configTypes(storeService.getMerchantStore(storeId));
        return ResultModel.ok().put("data",list);
    }

    @ApiOperation("门店配置删除")
    @GetMapping("/config/delete")
    public  ResultModel configurationDelete(@RequestParam("id") Long id){
        configurationService.configDelete(id);
        return ResultModel.ok("删除成功");
    }

}
